package com.hmdp.redis;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.utils.RedisConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
@RequiredArgsConstructor
public class CacheClient {

    private final StringRedisTemplate stringRedisTemplate;

    //reids过期时间
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        log.debug("缓存的id为{},缓存值{},缓存时间{}", key, value, time);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    //逻辑过期
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //缓存穿透
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit timeUnit) {
        //1.先查询redis是否存在
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //1.2存在直接返回
        if (StrUtil.isNotBlank(json)) {
            log.debug("命中缓存redis中的数据为{}", key);
            return JSONUtil.toBean(json, type);
        }

        //判断命中空值
        if (json != null) {
            return null;
        }

        //2不存在查询数据库
        R apply = dbFallback.apply(id);
        //2.查询数据库不存在
        if (apply == null) {
            //解决缓存穿透,写入空值
            log.debug("查询数据不存在");
            stringRedisTemplate.opsForValue().set(key, "", 2L, TimeUnit.MINUTES);
            return null;
        }
        //2.1存在写入缓存并且返回
        log.debug("进行了缓存重构");
        this.set(key, apply, time, timeUnit);
        return apply;
    }

    private static final ExecutorService threadPoll = Executors.newFixedThreadPool(10);

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit timeUnit) {
        //1.查询是否命中缓存
        String key = keyPrefix + id;
        String cache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(cache)) {
            //2.缓存没有命中
            log.debug("缓存没有命中");
            return null;
        }
        //3.命中缓存.进行反序列化
        RedisData redisData = JSONUtil.toBean(cache, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        //3.1判断是否逻辑过期
        //4.未过期
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            log.debug("时间没有过期" + redisData.getExpireTime() + "现在" + LocalDateTime.now());
            return r;
        }
        //5.已经过期
        //6.获取锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        //7.获取锁成功
        if (lock) {
            log.debug("获取锁成功开启线程");
            //7.1开启一个线程缓存的重建
            threadPoll.submit(() -> {
                try {
                    //查询
                    R apply = dbFallback.apply(id);
                    //写入redis
                    this.setWithLogicalExpire(key, apply, time, TimeUnit.MINUTES);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        //8.获取失败返回久的数据
        return r;

    }


    /**
     * 获取锁,给redis中存入setnx
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);

        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

}
